var dataservice = (function () {

    var apihost = "http://localhost:9001";

    var dataservice = {};

    dataservice.insert = function (sql, callback) {
        ajaxPostWithData(apihost + "/api/table/update", {
            sql: sql
        }, callback)
    };

    dataservice.update = function (sql, callback) {
        ajaxPostWithData(apihost + "/api/table/update", {
            sql: sql
        }, callback)
    };

    dataservice.deleteRecord = function(sql, callback){
        dataservice.update(sql, callback);
    };

    dataservice.queryList = function (sql, callback) {
        ajaxGetWithData(apihost + "/api/table/query", {
            sql: sql
        }, callback);
    };

    dataservice.getFirst = function (sql, callback) {
        dataservice.queryList(sql, function (list) {
            var item = null;
            if (list && list.length > 0) {
                item = list[0];
            }

            callback(item);
        });
    };

    dataservice.getCurrentUser = function (callback) {
        ajaxGet(apihost + "/api/currentuser", function (userid) {
            callback(userid);
        });
    };

    dataservice.login = function (userid, callback) {
        ajaxGet(apihost + "/api/login?userid=" + userid, callback);
    };

    dataservice.logout = function () {
        ajaxGet(apihost + "/api/logout");
    };

    function ajaxPostWithData(url, data, callback) {
        $.ajax({
            url: url,
            type: 'post',
            data: data,
            // 将XHR对象的withCredentials设为true
            xhrFields: {
                withCredentials: true
            },
            success: callback
        });
    }

    function ajaxGetWithData(url, data, callback) {
        $.ajax({
            url: url,
            data: data,
            // 将XHR对象的withCredentials设为true
            xhrFields: {
                withCredentials: true
            },
            success: callback
        });
    }

    function ajaxGet(url, callbak) {
        ajaxGetWithData(url, {}, callbak);
    }

    return dataservice;

})();